package kamikaze.service.product;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kamikaze.bean.Product;
import kamikaze.service.ErrorHandler;
import kamikaze.service.UserSession;
import kamikaze.utils.Database;
import kamikaze.utils.Database.Template;

public class CreateProductServlet extends HttpServlet {


	private static final long serialVersionUID = -8959830387607862463L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		new ErrorHandler(Arrays.asList("Method is not supported")).handle(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		try {
			final Product product = new Product();

			product.setCategory(req.getParameter("prodCat"));
			product.setName(req.getParameter("prodName"));
			product.setPicture(req.getParameter("prodPicture"));

			BigDecimal price = BigDecimal.ZERO;
			String strPrice = req.getParameter("prodPrice");
			if (strPrice != null) {
				Double dprice = Double.parseDouble(strPrice);
				price = BigDecimal.valueOf(dprice);
			}
			product.setPrice(price);
			product.setComment(req.getParameter("sellerComment"));
			product.setProductId(System.currentTimeMillis());
			product.setOwnerKey(UserSession.getFrom(req).getKey().getId());

			List<String> errors = product.validate();
			if (!errors.isEmpty()) {
				new ErrorHandler(errors).handle(req, resp);
			}else {
				Database.get().execute(new Template<Object>() {

					@Override
					public Object query(EntityManager em) {

						em.persist(product);

						return null;
					}
				});
				
				resp.sendRedirect("/retrieveProduct");
			}
						
		} catch (Exception ex) {
			new ErrorHandler(Arrays.asList(ex.getMessage())).handle(req, resp);
			return;
		}

	}

}
